<template>
  <j-modal
    switchFullscreen
    :fullscreen="false"
    destroyOnClose
    cancelText="关闭"
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :okButtonProps="{ class:{'jee-hidden': disableSubmit} }"
    @ok="handleOk"
    @cancel="handleCancel">
      <a-spin :spinning="confirmLoading" v-if="configInfo !== null">
        <div class="index-config-edit-container">
          <a-row>
            <a-col :span="24">
              <a-form-item label="配置名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input v-model="configInfo.configName" :disabled="type==='show'" placeholder="请输入配置名称"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="创建方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-dict-select-tag
                  type="list"
                  v-model="configInfo.configType"
                  dictCode="index_type"
                  :disabled="true"
                  placeholder="请选择创建方式" />
              </a-form-item>
            </a-col>
            <a-col :span="24">
            <a-form-item label="所属专题" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-tree-select
                multiple
                placeholder="请选择所属专题"
                style="width: 100%;"
                :replaceFields="replaceFields"
                :dropdownStyle="{ maxHeight: '200px', overflow: 'auto' }"
                :treeData="topicTypes"
                v-model="configInfo.topicType"
              >
              </a-tree-select>

            </a-form-item>
          </a-col>
            <a-col :span="24">
              <a-form-item label="是否启用" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-radio-group name="radioGroup" v-model="configInfo.status" :disabled="true">
                  <a-radio :value="'1'">启用</a-radio>
                  <a-radio :value="'0'">禁用</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-textarea v-model="configInfo.remark" :disabled="type==='show'" placeholder="请输入描述"></a-textarea>
              </a-form-item>
            </a-col>
          </a-row>
          <a-table
            ref="table"
            size="middle"
            bordered
            class="j-table-force-nowrap"
            rowKey="id"
            :scroll="{ x: true }"
            :pagination="false"
            :columns="columns"
            :dataSource="tableData">
            <template slot="type" slot-scope="text, record">
              <a-radio-group v-model="record.type" :disabled="true">
                <a-radio :style="radioStyle" :value="0">指标</a-radio>
                <a-radio :style="radioStyle" :value="1">维度</a-radio>
              </a-radio-group>
            </template>
            <template slot="dimensionType" slot-scope="text, record">
              <a-select
                v-if="record.type === 1"
                v-model="record.dimensionType"
                placeholder="请选择维度"
                :options="dimensionOptions"
                :disabled="true">
              </a-select>
            </template>
            <template slot="dimensionTypeTime" slot-scope="text, record">
              <j-dict-select-tag
                v-if="record.isDate === '1'"
                v-model="record.dimensionTypeTime"
                dictCode="dimension_date_type"
                placeholder="请选择时间维度类型"
                :triggerChange="true"
                :disabled="true" />
            </template>
            <template slot="name" slot-scope="text, record">
              <a-input
                class="table-input-class"
                v-if="record.type === 0"
                v-model="record.name"
                :disabled="type==='show'" />
            </template>
            <template slot="remark" slot-scope="text, record" >
              <a-input
              class="table-input-class"
                v-if="record.type === 0"
                v-model="record.remark"
                :disabled="type==='show'"/>
            </template>
            <template slot="unit" slot-scope="text, record">
              <a-input
              class="table-input-class"
                v-if="record.type === 0"
                v-model="record.unit"
                :disabled="type==='show'" />
            </template>
            <template slot="isPercent" slot-scope="text, record, index">
              <a-switch
                v-if="record.type === 0"
                v-model="record.isPercent"
                :disabled="type==='show'"
                @change="e => handleChange(e, index, 'isPercent')" />
            </template>
            <template slot="groupType" slot-scope="text, record, index">
              <a-select
                v-if="record.type === 0"
                v-model="record.groupType"
                placeholder="请选择指标聚合方式"
                :options="groupTypeOptions"
                :disabled="type==='show' || record.isPercent"
                @change="e => handleChange(e, index, 'groupType')">
              </a-select>
            </template>
          </a-table>
        </div>
      </a-spin>
      <template slot="footer">
        <a-button @click="handleCancel">关闭</a-button>
        <a-button type="primary" v-if="type==='edit'" @click="handleOk" :loading="confirmLoading">确定</a-button>
    </template>
  </j-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
export default {
  name: 'IndexConfigEditModal',
  data() {
    return {
      replaceFields: {
        children: 'childList',
        title: 'catalogName',
        key: 'id',
        value: 'id'
      },
      topicTypes: [],
      // 操作类型编辑还是查看
      type: '',
      // 配置信息
      configInfo: null,
      title: '',
      width: 800,
      visible: false,
      disableSubmit: false,
      confirmLoading: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      radioStyle: {
        padding: '0 5px'
      },
      // 维度下拉框
      dimensionOptions: [],
      // 聚合方式下拉框
      groupTypeOptions: [],
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '数据源',
          align: 'center',
          dataIndex: 'dataSourceName'
        },
        {
          title: '表名',
          align: 'center',
          dataIndex: 'tableName'
        },
        {
          title: '字段名',
          align: 'center',
          dataIndex: 'tableColumn'
        },
        {
          title: '数据类型',
          align: 'center',
          dataIndex: 'dataType'
        },
        {
          title: '长度',
          align: 'center',
          dataIndex: 'columnLength'
        },
        {
          title: '小数位数',
          align: 'center',
          dataIndex: 'scale'
        },
        {
          title: '维度/指标',
          align: 'center',
          dataIndex: 'type',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '对应维度',
          align: 'center',
          dataIndex: 'dimensionType',
          scopedSlots: { customRender: 'dimensionType' }
        },
        {
          title: '时间维度类型',
          align: 'center',
          dataIndex: 'dimensionTypeTime',
          scopedSlots: { customRender: 'dimensionTypeTime' }
        },
        {
          title: '指标名称',
          align: 'center',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
          scopedSlots: { customRender: 'remark' }
        },
        {
          title: '统计单位',
          align: 'center',
          dataIndex: 'unit',
          scopedSlots: { customRender: 'unit' }
        },
        {
          title: '是否率值',
          align: 'center',
          dataIndex: 'isPercent',
          scopedSlots: { customRender: 'isPercent' }
        },
        {
          title: '聚合方式',
          align: 'center',
          dataIndex: 'groupType',
          scopedSlots: { customRender: 'groupType' }
        }
      ],
      tableData: []
    }
  },
  created() {
    this.loadDimensionOptions()
    this.loadGroupTypeOptions()
    this.getTopicTypes()
  },
  mounted() {

  },
  methods: {
    getTopicTypes() {
      this.topicTypes = []
      getAction('/index/config/queryIndexCatalog', {}).then((res) => {
        if (res.success) {
          this.topicTypes = res.result
        }
      })
    },
    show(id) {
      console.log('show', id)
      this.type = 'show'
      this.title = '查看指标配置'
      this.initData(id)
    },
    edit(id) {
      console.log('edit', id)
      this.type = 'edit'
      this.title = '编辑指标配置'
      this.initData(id)
    },
    initData(id) {
      this.visible = true
      this.tableData = []
      this.$get('/index/config/loadIndexConfig?configId=' + id).then(res => {
        if (res.success) {
          this.configInfo = JSON.parse(res.result.configData)

          this.configInfo.dimensionInfos.map(item => {
            item.type = 1
            item.dataSourceName = this.configInfo.dataSource

            if (item.isDate === '1') {
              item.dimensionTypeTime = item.dimensionType
              item.dimensionType = 'time'
            }

            this.tableData.push({ ...item })
          })

          if (this.configInfo.topicType) {
            this.configInfo.topicType = this.configInfo.topicType.split(',')
          }

          this.configInfo.indexInfos.map(item => {
            item.type = 0
            item.isPercent = item.isPercent === 1
            item.dataSourceName = this.configInfo.dataSource
            item.groupType = item.groupType
            this.tableData.push({ ...item })
          })
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleOk() {
      if (this.configInfo.configName.trim() === '') {
        this.$message.warning('请输入配置名称!')
        return
      }
      let record = this.tableData.find(item => item.type === 0 && item.name.trim() === '')
      if (record) {
        this.$message.warning(`${record.tableName}表的${record.tableColumn}字段未输入指标名称`)
        return
      }
      record = this.tableData.find(item => item.type === 0 && !item.isPercent && item.groupType === undefined)
      if (record) {
        this.$message.warning(`${record.tableName}表的${record.tableColumn}字段未选择聚合方式`)
        return
      }

      this.confirmLoading = true
      const dimensionInfoList = []
      const indexInfoList = []
      this.tableData.map(item => {
        const obj = { ...item }

        if (obj.type === 0) {
          obj.isPercent = obj.isPercent ? 1 : 0
          if (obj.scale === undefined) delete obj.scale
          delete obj.type
          indexInfoList.push(obj)
        } else {
          obj.dimensionType = obj.isDate === '0' ? obj.dimensionType : obj.dimensionTypeTime
          delete obj.type
          dimensionInfoList.push(obj)
        }
      })

      const submitObj = JSON.parse(JSON.stringify(this.configInfo))
      submitObj.dimensionInfoList = dimensionInfoList
      submitObj.indexInfoList = indexInfoList

      if (submitObj.topicType != null && submitObj.topicType.length > 0) {
        submitObj.topicType = submitObj.topicType.join(',')
      }

      submitObj.dataSource = null

      console.log(submitObj)

      this.$post('/index/config/editIndexConfig', submitObj).then(res => {
        if (res.success) {
          this.$message.success('指标修改成功')
          this.$emit('ok')
          this.visible = false
        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    },
    handleCancel() {
      this.$emit('cancel')
      this.visible = false
    },
    loadDimensionOptions() {
      this.$get('/dimension/scSituationDimensionType/list?pageNo=1&pageSize=1000').then(res => {
        this.dimensionOptions = [
          {
            value: 'time',
            title: '时间维度'
          }
        ]
        res.result.records.map(item => {
          this.dimensionOptions.push({
            value: item.id,
            title: item.dimensionName
          })
        })
      })
    },
    loadGroupTypeOptions() {
      this.$get('/sys/dict/getDictItems/index_group_type').then(res => {
        res.result.map(item => {
          if (item.status) {
            this.groupTypeOptions.push({
              value: item.value,
              title: item.text
            })
          }
        })
      })
    },
    handleChange(value, index, name) {
      if (name === 'isPercent') this.tableData[index].groupType = undefined
    }
  }
}
</script>
<style lang="less">
.index-config-edit-container {
  .ant-select {
    min-width: 180px;
  }
  .table-input-class {
    min-width: 150px;
  }
}
</style>
